package com.xxh.securitydemo.compoent;
import com.xxh.securitydemo.model.UmsAdmin;
import com.xxh.securitydemo.model.UmsResource;
import com.xxh.securitydemo.service.AdminService;
import com.xxh.securitydemo.service.UmsResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class AdminUserDetailService implements UserDetailsService {

    @Autowired
    AdminService adminService;

    @Resource
    UmsResourceService umsResourceService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UmsAdmin admin = adminService.getAdminByUsername(username);
        if(admin!=null){
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            //加载用户权限
            List<UmsResource> resources = umsResourceService.loadResourceByUserID(admin.getId());
            for (UmsResource r:resources){
                String role=r.getId()+":"+r.getName();
                grantedAuthorities.add(new SimpleGrantedAuthority(role));
            }
            return new User(admin.getUsername(),admin.getPassword(),grantedAuthorities);
        }else {
            throw  new RuntimeException("用户不存在");
        }
    }
}
